<template>
  <div class="container">
    <div class="card">
      <div class="header">
        <div style="color: #A71E32">评估列表</div>
        <div class="operate">
          <!--
          <el-select v-model="searchProp" style="width: 280px;">
            <el-option v-for="item in searchOptions"
                       :key="item.value"
                       :label="item.label"
                       :value="item.value"/>
          </el-select>
          -->
          <el-input v-model="searchData" placeholder="输入筛选条件" :prefix-icon="Search" @change="toFilterData"></el-input>
          <el-pagination background layout="sizes, prev, pager, next"
                         :total="totalCount" v-model:page-size="pageSize" :page-sizes="[200, 400, 600, 800, 1000]"
                         @size-change="handleSizeChange" @current-change="onCurrentClick"/>
          <el-button type="warning" @click="reloadData">刷新</el-button>
          <el-button type="primary" @click="addParty">新增</el-button>
        </div>
      </div>
      <div class="body">
        <el-table class="party" :data="partyTable.filter(data=> !searchData || data.partyName.toLowerCase().includes(searchData.toLowerCase()) || data.partyTime.toLowerCase().includes(searchData.toLowerCase()))" border :key="needFlashData"
                  :header-cell-style="{'text-align': 'center'}"
                  empty-text="请添加党建信息" style="width: 100%;height: 100%" @row-dblclick="rowDblclick">
          <el-table-column type="index" label="序号" align="center" width="80"/>
          <el-table-column prop="partyName" label="支部名称" align="center" min-width="100"/>
          <el-table-column prop="partyTime" label="年度" align="center" min-width="60"/>
          <!--
          <el-table-column prop="partyType" label="类别" align="center" min-width="80"/>
          <el-table-column prop="projectName" label="项目" align="left" min-width="100"/>
          <el-table-column prop="checkey" label="检查要点" align="left" min-width="100">
            <template #default="scope" style="text-align: left">
              <div v-for="(val,key)  in scope.row.checkey">
                {{key+1}}.{{val}}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="execute" label="主要评价指标" align="center" min-width="300">
            <el-table-column prop="execute1" label="工作推进与制度执行" align="left" min-width="100">
              <template #default="scope">
                <el-select v-if="needToEdit.includes(scope.row.partyName + scope.row.partyTime)"
                           v-model="scope.row.execute1" class="m-2" multiple
                           @change="changeSelect">
                  <el-option
                      v-for="item in adjustEvaluation(scope.row.evaluation1)"
                      :key="item"
                      :label="item"
                      :value="item"/>
                </el-select>
                <div v-else v-for="(val) in orderExecute(scope.row.execute1)">
                  {{JSON.parse(val).data}}
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="execute1" label="备注" align="left" min-width="100">
              <template #default="scope">
                <div v-for="(val,key) in orderExecute(scope.row.execute1)">
                  {{JSON.parse(val).remark ? key+1 +'.' +JSON.parse(val).remark : ''}}
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="execute2" label="工作质量与实际成效" align="left" min-width="100">
              <template #default="scope">
                <el-select v-if="needToEdit.includes(scope.row.partyName + scope.row.partyTime)"
                           v-model="scope.row.execute2" class="m-2" multiple >
                  <el-option
                      v-for="item in adjustEvaluation(scope.row.evaluation2)"
                      :key="item"
                      :label="item"
                      :value="item"/>
                </el-select>
                <div v-else v-for="(val) in orderExecute(scope.row.execute2)">
                  {{JSON.parse(val).data}}
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="execute2" label="备注" align="left" min-width="100">
              <template #default="scope">
                <div v-for="(val,key) in orderExecute(scope.row.execute2)">
                  {{JSON.parse(val).remark ? key+1 +'.' +JSON.parse(val).remark : ''}}
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="execute3" label="有无严禁发生的行为" align="left" min-width="100">
              <template #default="scope">
                <el-select v-if="needToEdit.includes(scope.row.partyName + scope.row.partyTime)"
                           v-model="scope.row.execute3" class="m-2" multiple >
                  <el-option
                      v-for="item in adjustEvaluation(scope.row.evaluation3)"
                      :key="item"
                      :label="item"
                      :value="item"/>
                </el-select>
                <div v-else v-for="(val) in orderExecute(scope.row.execute3)">
                  {{JSON.parse(val).data}}
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="execute3" label="备注" align="left" min-width="100">
              <template #default="scope">
                <div v-for="(val,key) in orderExecute(scope.row.execute3)">
                  {{JSON.parse(val).remark ? key+1 +'.' +JSON.parse(val).remark : ''}}
                </div>
              </template>
            </el-table-column>
          </el-table-column>
          <el-table-column prop="bonus" label="加分项" align="left" min-width="100">
            <template #default="scope">
              <el-select v-if="needToEdit.includes(scope.row.partyName + scope.row.partyTime)"
                         v-model="scope.row.bonus" class="m-2" multiple >
                <el-option
                    v-for="item in bonusOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"/>
              </el-select>
              <div v-else v-for="(val,key) in orderExecute(scope.row.bonus)">
                {{key+1}}.{{JSON.parse(val).data}}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="bonus" label="备注" align="left" min-width="100">
            <template #default="scope">
              <div v-for="(val,key) in orderExecute(scope.row.bonus)">
                {{JSON.parse(val).remark ? key+1 +'.' +JSON.parse(val).remark : ''}}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="negative" label="减分项" align="left" min-width="100">
            <template #default="scope">
              <el-select v-if="needToEdit.includes(scope.row.partyName + scope.row.partyTime)"
                         v-model="scope.row.negative" class="m-2" multiple >
                <el-option
                    v-for="item in negativeOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"/>
              </el-select>
              <div v-else v-for="(val,key) in orderExecute(scope.row.negative)">
                {{key+1}}.{{JSON.parse(val).data}}
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="negative" label="备注" align="left" min-width="100">
            <template #default="scope">
              <div v-for="(val,key) in orderExecute(scope.row.negative)">
                {{JSON.parse(val).remark ? key+1 +'.' +JSON.parse(val).remark : ''}}
              </div>
            </template>
          </el-table-column>
          -->
          <el-table-column prop="score" label="等次" align="center" width="100">
            <template #default="scope">
              <el-select v-model="scope.row.scoreLabel" class="m-2" placeholder="等次" disabled>
                <el-option
                    v-for="item in executeOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"/>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="censorScore" label="审查等次" align="center" width="100">
            <template #default="scope">
              <el-select v-model="scope.row.censorScoreLabel" class="m-2" placeholder="等次" disabled>
                <el-option
                    v-for="item in executeOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"/>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="operate" label="操作" align="center" width="200">
            <template #default="scope">
              <div style="display: flex;justify-content: space-around; flex-direction: row-reverse;gap: 20px">
                <el-link :underline="false" type="danger" v-on:click="deleteOperate(scope.row)">删除</el-link>
                <el-link v-if="needToEdit.includes(scope.row.partyName + scope.row.partyTime)" :underline="false" type="primary" v-on:click="savePartyData(scope.row)">保存</el-link>
                <el-link v-else :underline="false" type="primary" v-on:click="editOperate(scope.row)">评估</el-link>
                <el-link :underline="false" type="primary" v-on:click="showOperate(scope.row)">详情</el-link>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <party-new @reload="reloadData"></party-new>
    <party-info v-model:visible="showPartyInfo" :data="editPartyInfo" v-model:operate="editOrShowParty" @reload:data="reloadData"></party-info>
  </div>
</template>

<script lang="ts">
import { Search } from '@element-plus/icons-vue'
import {onMounted, ref, watch} from "vue";
import {IParty, IProperty} from "@/iwb/IParty";
import PartyNew from "@/components/party/PartyNew.vue";
import {useConfigStore} from "@/store/config";
import {storeToRefs} from "pinia";
import {TableColumnCtx} from "element-plus";
import {deletePartyBuilding, getPartyBuilding, updatePartyBuilding} from "@/api/party";
import {useUserStore} from "@/store/user";
import {DialogUtils} from "@/utils/DialogUtils";
import {Utils} from "@/utils/utils";
import PartyInfo from "@/components/party/PartyInfo.vue";

export default {
  name: "index",
  components: {PartyInfo, PartyNew},
  setup() {
    const pageIndex = ref(0);
    const pageSize = ref(200);
    const totalCount = ref(0);
    const needFlashData = ref(false);
    const partyTable = ref([] as Array<IParty>);
    const partyBuilding = ref([] as Array<IParty>);
    const editPartyInfo = ref([] as Array<IParty>);
    const useConfig = useConfigStore()
    const {showPartyNew} = storeToRefs(useConfig);
    const needToEdit = ref([] as Array<string>);
    const showPartyInfo = ref(false);
    const editOrShowParty = ref('edit');
    const searchProp = ref('');
    const searchData = ref('');

    const executeOptions = [{
      value: '优秀',
      label: '优秀',
    },{
      value: '良好',
      label: '良好',
    },{
      value: '一般',
      label: '一般',
    },{
      value: '不力',
      label: '不力',
    }];

    const bonusOptions = [{
      value: '加分1',
      label: '加分1'
    },{
      value: '加分2',
      label: '加分2'
    }];

    const negativeOptions = [{
      value: '减分1',
      label: '减分1'
    },{
      value: '减分2',
      label: '减分2'
    }]

    const searchOptions = [{
      value: '支部名称',
      label: '支部名称'
    },{
      value: '年度',
      label: '年度'
    }]

    /**
     * 过滤数据
     */
    const toFilterData = () => {
      if (searchProp.value === '支部名称') {

      }
    }

    const orderExecute = (execute: Array<string>) => {
      if (execute) {
        return execute.sort();
      }
      return [];
    }

    const adjustEvaluation = (evaluation: any) => {
      if (evaluation) {
        const adjustResult = [];
        for (let i=0; i<evaluation.length; ++i) {
          adjustResult.push(i+1 + '.' + evaluation[i]);
        }
        return adjustResult;
      }
      return [];
    }

    const handleSizeChange = (size: number) => {
      pageIndex.value = 0;
      totalCount.value = 0;
      const index = pageIndex.value;
      pageSize.value = size;
      const userStore = useUserStore();
      if (totalCount.value > index * size || pageIndex.value ===0) {
        getPartyBuilding(pageIndex.value + 1, pageSize.value).then((res: any) => {
          totalCount.value = res.data.total;
          res.data.buildings.forEach((item: IParty) => {
            item.scoreLabel = adjustScore(item.score);
          })
          partyBuilding.value = res.data.buildings;
        });
      }
    }

    const onCurrentClick = (value: number) => {
      console.log(value);
      const index = value - 1;
      const size = pageSize.value;
      pageIndex.value = index;
      const userStore = useUserStore();
      if (totalCount.value > index * size || pageIndex.value ===0) {
        getPartyBuilding(pageIndex.value + 1, pageSize.value).then((res: any) => {
          totalCount.value = res.data.total;
          res.data.buildings.forEach((item: IParty) => {
            item.scoreLabel = adjustScore(item.score);
          })
          partyBuilding.value = res.data.buildings;
        });
      }
    }

    /**
     * 新镇党建信息
     */
    const addParty = () => {
      showPartyNew.value = true;
    }

    const deleteOperate = (row: any) => {
      DialogUtils.showMessageBox('温馨提示', '是否确定删除党建信息:['+row.partyName+','+row.partyTime+']', {type: 'warning'}).then(()=>{
        deletePartyBuilding(row.partyName, row.partyTime).then(()=>{
          reloadData();
        });
      })
    }

    const rowDblclick = (row: any, column: any, event: any) => {
      showOperate(row);
    }

    const editOperate = (row: any) => {
      //needToEdit.value.push(row.partyName + row.partyTime);
      showPartyInfo.value = true;
      editPartyInfo.value = partyBuilding.value.filter(item => item.partyName+item.partyTime === row.partyName + row.partyTime);
      editOrShowParty.value = 'edit';
      console.warn(editPartyInfo.value);
    }

    const showOperate = (row: any) => {
      editOrShowParty.value = 'show';
      showPartyInfo.value = true;
      editPartyInfo.value = partyBuilding.value.filter(item => item.partyName+item.partyTime === row.partyName + row.partyTime);
    }

    const computeScore = (partyInfo: Array<IParty>) => {
      let allElementEvaluation1 = 0;  //工作推进与制度执行方面
      let allElementEvaluation2 = 0;  //工作质量与实际成效方面
      let allElementEvaluation3 = 0;  //严禁发生的行为方面
      let haveElementExecute1 = 0;    //工作推进与制度执行方面
      let haveElementExecute2 = 0;    //工作质量与实际成效方面
      let haveElementExecute3 = 0;    //严禁发生的行为方面
      let hasOneVoteNo = false;       //是否存在一票否决
      let hasBonus = false;
      let hasNegative = false;
      partyInfo.forEach((item: IParty) => {
        allElementEvaluation1 += item.evaluation1 ? item.evaluation1.length : 0;
        allElementEvaluation2 += item.evaluation2 ? item.evaluation2.length : 0;
        allElementEvaluation3 += item.evaluation3 ? item.evaluation3.length : 0;
        haveElementExecute1 += item.execute1 ? item.execute1.length : 0;
        haveElementExecute2 += item.execute2 ? item.execute2.length : 0;
        haveElementExecute3 += item.execute3 ? item.execute3.length : 0;
        //直接否决
        if (item.partyType === '坚持党对军队绝对领导方面' || item.partyType === '领导推进备战打仗方面') {
          hasOneVoteNo = hasOneVoteNo || item.execute3.length > 0;
        }
        //判断是否有加减分项目
        if (item.bonus) {
          hasBonus = hasBonus || item.bonus.length > 0;
        }
        if (item.negative) {
          hasNegative = hasNegative || item.negative.length > 0;
        }
      })
      /**
       * 计算等次
       */
      if (hasOneVoteNo) {
        //如果存在一票否决发生的问题
        partyInfo.forEach((item: IParty) => {
          item.score = 0;
          item.scoreLabel = adjustScore(item.score);
        });
      } else {
        let score = 0;
        const executeScore1 = haveElementExecute1 * 100 / allElementEvaluation1;
        const executeScore2 = haveElementExecute2 * 100 / allElementEvaluation2;
        const executeScore3 = haveElementExecute3 * 100 / allElementEvaluation3;
        //优秀
        if (executeScore1 > 90 && executeScore2 > 90) {
          score = 91;
        } else if (executeScore1 > 80 && executeScore2 > 80) {
          //良好
          score = 81;
        } else if (executeScore1 > 70 && executeScore2 > 70) {
          //一般
          score = 71
        } else {
          //不力
          score = 61;
        }
        //判断是否有加减分项目
        score += hasBonus ? 10 : 0;
        score -= hasNegative ? 10 : 0;
        //设置总分
        partyInfo.forEach((item: IParty) => {
          item.score = score;
          item.scoreLabel = adjustScore(item.score);
        });
      }
      return partyInfo;
    }

    const savePartyData = (row: any) => {
      needToEdit.value = needToEdit.value.filter(item => item !== row.partyName + row.partyTime);
      let sourceParty = partyBuilding.value.filter(item => item.partyName+item.partyTime === row.partyName + row.partyTime);
      computeScore(sourceParty);
      const needToSave = Utils.cloneObject(sourceParty);
      needToSave.forEach((item: any) => {
        item.checkey = undefined;
        item.evaluation1 = undefined;
        item.evaluation2 = undefined;
        item.evaluation3 = undefined;
      })
      updatePartyBuilding({total: needToSave.length, updateBuilding: JSON.stringify(needToSave)}).catch(error => {
        console.error(error);
        DialogUtils.showErrorBox('温馨提示', '党建信息更新失败');
      })
    }

    interface SpanMethodProps {
      row: IParty
      column: TableColumnCtx<IParty>
      rowIndex: number
      columnIndex: number
    }
    /**
     const objectSpanMethod = ({
                                row,
                                column,
                                rowIndex,
                                columnIndex,
                              }: SpanMethodProps) => {
      const spanNameNum = partyBuilding.value.filter(item => item.partyName+item.partyTime === row.partyName + row.partyTime).length;
      const spanTypeNum = partyBuilding.value.filter(item => item.partyName+item.partyTime+item.partyType === row.partyName+row.partyTime+row.partyType).length;

      if (columnIndex === 1 || columnIndex === 2 || columnIndex === 9 || columnIndex === 10 || columnIndex === 11 || columnIndex === 12) {
        if (rowIndex % spanNameNum === 0) {
          return {
            rowspan: spanNameNum,
            colspan: 1,
          }
        } else {
          return {
            rowspan: 0,
            colspan: 0,
          }
        }
      } else if (columnIndex === 3) {
        if (rowIndex % spanTypeNum === 0) {
          return {
            rowspan: spanTypeNum,
            colspan: 1,
          }
        } else {
          return {
            rowspan: 0,
            colspan: 0,
          }
        }
      }
    }
     **/

    const objectSpanMethod = ({
                                row,
                                column,
                                rowIndex,
                                columnIndex,
                              }: SpanMethodProps) => {

      let num = 1
      // 根据columnIndex判断需要判断值是否相等的字段
      if (columnIndex === 0 || columnIndex === 1 || columnIndex === 2 || columnIndex === 3  || columnIndex === 4 || columnIndex === 14 || columnIndex === 15 || columnIndex === 16 || columnIndex === 17) {
        num = recursionRowSpan(row, rowIndex, 'partyName', partyBuilding.value)
      } else if (columnIndex === 3) {
        num = recursionRowSpan(row, rowIndex, 'partyType', partyBuilding.value)
      }
      return {
        rowspan: num,
        colspan: 1,
      };
    }
    let nowRowSpan = 1;
    const recursionRowSpan = (row: IParty, rowIndex: number, str: string, data: Array<IParty>): number => {
      let num: number = 0;
      let isEqual: boolean = false;
      let isNextEqual: boolean = false;
      if (str === 'partyName') {
        isEqual = rowIndex > 0 && row.partyName == data[rowIndex - 1].partyName;
        isNextEqual = rowIndex + 1 < data.length && row.partyName == data[rowIndex + 1].partyName;
      } else if (str === 'partyTime') {
        isEqual = rowIndex > 0 && row.partyTime == data[rowIndex - 1].partyTime;
        isNextEqual = rowIndex + 1 < data.length && row.partyTime == data[rowIndex + 1].partyTime;
      } else if (str === 'partyType') {
        isEqual = rowIndex > 0 && row.partyType == data[rowIndex - 1].partyType;
        isNextEqual = rowIndex + 1 < data.length && row.partyType == data[rowIndex + 1].partyType;
      }

      /**
       * 判断上一行字段的值与该行值是否一致
       */
      if (nowRowSpan === 1 && isEqual) {
        return 0
      }
      /**
       * 判断下一行字段的值与该行值是否一致
       */
      if (isNextEqual) {
        nowRowSpan += 1;
        num = rowIndex + 1;
        return recursionRowSpan(data[num], num, str, data);
      } else {
        num = nowRowSpan;
        nowRowSpan = 1;
        return num;
      }
    }

    const fetchData = () => {
      if (totalCount.value > pageIndex.value * pageSize.value || pageIndex.value ===0) {
        getPartyBuilding(pageIndex.value + 1, pageSize.value).then((res: any) => {
          totalCount.value = res.data.total;
          res.data.buildings.forEach((item: IParty) => {
            item.scoreLabel = adjustScore(item.score);
            item.censorScoreLabel = adjustScore(item.censorScore);
          })
          partyBuilding.value = res.data.buildings;
          //console.warn(partyBuilding.value);
        });
      }
    }

    const reloadData = () => {
      pageIndex.value = 0;
      totalCount.value = 0;
      const index = pageIndex.value;
      const size = pageSize.value;
      if (totalCount.value > index * size || pageIndex.value ===0) {
        getPartyBuilding(pageIndex.value + 1, pageSize.value).then((res: any) => {
          totalCount.value = res.data.total;
          res.data.buildings.forEach((item: IParty) => {
            item.scoreLabel = adjustScore(item.score);
            item.censorScoreLabel = adjustScore(item.censorScore);
          })
          partyBuilding.value = res.data.buildings;
        });
      }
    }

    const changeSelect = (item: any) => {
      let isSerialNumber = true;
      if (item) {
        item.forEach( (data: any) => {
          isSerialNumber = isSerialNumber && Utils.startSerialNumber(data);
        })
      }
      if (!isSerialNumber) {
        DialogUtils.showWarningBox('警告提示', '新增选项需要以数字加点开头');
      }
    }

    const adjustScore = (score: number) => {
      return score > 90 ? '优秀': score > 80 ? '良好': score > 70 ? '一般' : '不力';
    }

    watch(() => partyBuilding.value, (newData, oldData) => {
      partyTable.value = [];
      newData.forEach(data => {
        const party = partyTable.value.filter(item => item.partyName+item.partyTime === data.partyName + data.partyTime);
        if (party.length <= 0 ) {
          partyTable.value.push(data);
        }
      })
    });

    onMounted(() => {
      fetchData();
    })

    return {
      Search,
      pageSize,
      totalCount,
      needFlashData,
      partyTable,
      partyBuilding,
      editPartyInfo,
      searchProp,
      searchData,
      executeOptions,
      bonusOptions,
      negativeOptions,
      searchOptions,
      needToEdit,
      showPartyInfo,
      editOrShowParty,
      handleSizeChange,
      onCurrentClick,
      toFilterData,
      addParty,
      deleteOperate,
      orderExecute,
      rowDblclick,
      editOperate,
      showOperate,
      savePartyData,
      objectSpanMethod,
      adjustEvaluation,
      reloadData,
      changeSelect,
      adjustScore
    }
  }
}
</script>

<style scoped lang="scss">
@import "src/styles/variable";

.container {
  width: auto;
  height: 100%;
  padding: 10px;
  background-color: $color-background-base;
  border: 0;
  box-sizing: border-box;
}

.header {
  padding: 10px 24px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: 1px solid $color-border-base;
}

.card {
  width: 100%;
  height: 100%;
  background-color: $color-sub-background-base;
  overflow: auto;
}

.operate {
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid $color-border-base;
  gap: 5px;
}

.body {
  height: calc(100% - 54px);

  .party {
    width: auto;
  }
}
</style>